package com.lius.SpringBootStart.filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.lius.SpringBootStart.domain.User;
import com.lius.SpringBootStart.service.UserService;
import com.lius.SpringBootStart.utils.JsonData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

//@WebFilter(urlPatterns = "/api/v1/pri/*", filterName = "loginFilter")
public class LoginFilter implements Filter {

    @Autowired
    private UserService userService;

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        // 强转
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse resp = (HttpServletResponse) servletResponse;

        // 获取传入token
        String token = req.getHeader("token");
        System.out.println(userService.getUser());

        if (!StringUtils.hasLength(token)) {
            token = req.getParameter("token");
        }

        if (!StringUtils.hasLength(token)) {
            renderJson(resp, JsonData.buildError("参数异常，未定义token", -10));
        } else {
            // 判断token是否合法 :TODO
            User user = userService.getUserByToekn(token);
            if (user != null) {
                filterChain.doFilter(servletRequest, servletResponse);
            }
        }
        renderJson(resp, JsonData.buildError("错误的token", -12));
    }

    private void renderJson(HttpServletResponse response, JsonData jsonData) {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");

        try (PrintWriter writer = response.getWriter()) {
            // 因为println只能输出String，需要将JosnData对象转为String
            String json = (new ObjectMapper()).writeValueAsString(jsonData);
            writer.println(json);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }
}
